package edu.gatech.gitmad.catbug.formation;

public class MyData {
	public static final long UPLOAD_DELAY = 30000;
	
	private double lat;
	private double lon;
	private boolean sending;
	private Thread thread;
	private UpdateSender updateSender;
	
	public MyData() {
		lat = 0.0;
		lon = 0.0;
		sending = false;
		updateSender = new UpdateSender();
	}
	
	public void startSending() {
		if (!sending) {
			sending = true;
			thread = new Thread(updateSender);
			thread.start();
		}
	}
	
	public void forceUpdate() {
		updateSender.sendUpdate();
	}
	
	public void stopSending() {
		sending = false;
		if (thread != null) {
			thread.interrupt();
		}
	}

	
	private class UpdateSender implements Runnable {
		
		public void sendUpdate() {
			lat = MapActivity.mCurrentLat;
			lon = MapActivity.mCurrentLong;
			
			String[] vars = {"GroupID", "MemberID", "Lon", "Lat", "LastUpdate", "MemberName"};
			String[] vals = {SessionData.getGroupID(), SessionData.getMemberID(), lon+"", lat+"", 
							System.currentTimeMillis()+"", SessionData.getMemberName()};
			String url = String.format("%s/sendupdate.php?", SessionData.databaseurl);
			String params = String.format("%s=%s", vars[0], vals[0]);
			for (int i=1; i<vars.length; i++) {
				params += String.format("&%s=%s", vars[i], vals[i]);
			}
			url += params;
			
			HTTPGet get = new HTTPGet(url);
			get.execute();
		}
		
		public void run() {
			while (sending) {
				sendUpdate();
				try {
					Thread.sleep(UPLOAD_DELAY);
				}
				catch (InterruptedException e) {
					
				}
			}
		}
	}
}
